import {app} from 'electron'
import axios, {AxiosRequestConfig, AxiosResponse} from 'axios'
import fs from 'fs'
import path from 'path'

export type ServiceKey = 'SOURCE' | string

export interface ApiRequest {
  service: ServiceKey
  method: 'GET' | 'POST' | 'PUT' | 'DELETE'
  path: string
  params?: Record<string, any>
  body?: any
  headers?: Record<string, string>
}

interface StandardResponse<T = any> {
  code: number
  message: string
  data: T
}

function readServicesConfig(): Record<string, string> {
  // 在开发与生产环境下都从应用根路径下的 electron/services.json 读取
  const configPath = path.join(app.getAppPath(), 'electron', 'services.json')
  try {
    const raw = fs.readFileSync(configPath, 'utf8')
    return JSON.parse(raw)
  } catch (e) {
    console.error('读取微服务配置失败:', e)
    return {}
  }
}

const servicesCache = readServicesConfig()

function getBaseUrl(service: ServiceKey): string | undefined {
  return servicesCache[service]
}

export async function requestApi<T = any>(req: ApiRequest): Promise<T> {
  const baseURL = getBaseUrl(req.service)
  if (!baseURL) {
    throw new Error(`未配置微服务地址: ${req.service}`)
  }

  const config: AxiosRequestConfig = {
    baseURL,
    url: req.path,
    method: req.method,
    params: req.params,
    data: req.body,
    headers: {
      'Content-Type': 'application/json',
      ...(req.headers || {}),
    },
    timeout: 30000,
  }

  const resp: AxiosResponse<StandardResponse<T> | T> = await axios.request(config)
  const payload = resp.data
  if (payload && typeof payload === 'object' && 'code' in (payload as any)) {
    const std = payload as StandardResponse<T>
    // 兼容后端返回 code=200 或 code=20000 的成功格式
    if (std.code === 200 || std.code === 20000) return std.data
    throw new Error(std.message || '请求失败')
  }
  // 如果服务未返回统一格式，直接返回
  return payload as T
}